package middleware

import (
	"fmt"
	"gin.study/config"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"path"
	"time"
)

// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {

	logFilePath := config.LOGFILEPATH
	logFileName := config.LOGFILENAME

	//日志文件
	fileName := path.Join(logFilePath, logFileName)

	//实例化
	logger := logrus.New()

	//写入文件
	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("err", err)
	}
	gin.DefaultWriter = io.MultiWriter(file)  //启动日志

	//设置输出
	logger.Out = file

	//设置日志级别
	logger.SetLevel(logrus.DebugLevel)

	//设置日志格式
	logger.SetFormatter(&logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05"})

	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()

		// 处理请求
		c.Next()

		// 结束时间
		endTime := time.Now()

		// 执行总时间
		latencyTime := endTime.Sub(startTime)

		// 请求方式
		reqMethod := c.Request.Method

		// 请求路由
		reqUri := c.Request.RequestURI

		// 状态码
		statusCode := c.Writer.Status()

		// 请求IP
		clientIP := c.ClientIP()

		// 日志格式
		logger.Debugf("| statusCode=%3d | latencyTime=%13v | clientIP=%15s | reqMethod=%6s | reqUri=%10s |",
			statusCode,
			latencyTime,
			clientIP,
			reqMethod,
			reqUri,
		)
		//logger.WithFields(logrus.Fields{
		//	"statusCode":statusCode,
		//	"latencyTime":latencyTime,
		//	"clientIP":clientIP,
		//	"reqMethod":reqMethod,
		//	"reqUri":reqUri,
		//}).Debug()
	}
}

// 日志记录到 MongoDB
func LoggerToMongo() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

// 日志记录到 ES
func LoggerToES() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

// 日志记录到 MQ
func LoggerToMQ() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}


